package com.yixun.qfbao.controller;

import com.yixun.qfbao.api.service.CustomerTKService;
import com.yixun.qfbao.api.service.RoleResourcesService;
import com.yixun.qfbao.apidto.GetCustomerPageReqDto;
import com.yixun.qfbao.apidto.base.CommonReqDTO;
import com.yixun.qfbao.constant.RedisKeyConstant;
import com.yixun.qfbao.model.Customer;
import com.yixun.qfbao.model.OperationLog;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.dto.CustomerDto;
import com.yixun.qfbao.model.dto.OperationLogDto;
import com.yixun.qfbao.request.BaseRequest;
import com.yixun.qfbao.request.GenericIdRequest;
import com.yixun.qfbao.request.PageRequest;
import com.yixun.qfbao.request.customer.SaveOrEditCustomerReqDto;
import com.yixun.qfbao.response.BaseResponse;
import com.yixun.qfbao.response.PageResult;
import com.yixun.qfbao.response.customer.CustomerConvert;
import com.yixun.qfbao.response.customer.CustomerPageResDto;
import com.yixun.qfbao.service.OperationLogService;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.util.RedisUtil;
import com.yixun.qfbao.util.WxAccessTokenCacheUtils;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@ResponseBody
@RequestMapping("/test")
public class TestController {

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private CustomerTKService customerTKService;
    @Autowired
	WxAccessTokenCacheUtils wxAccessTokenCacheUtils;
    @Autowired
    PartnerInfoService partnerInfoService;
    @Autowired
    RoleResourcesService roleResourcesService;

    @PostMapping("/getOperationById")
    public BaseResponse<OperationLog> getOperationById(@RequestBody BaseRequest<GenericIdRequest> reqDto){
        BaseResponse<OperationLog> response = new BaseResponse<>();
        OperationLog operationLog = operationLogService.selectById(reqDto.getData().getId());
        response.setData(operationLog);
        response.setCode(ResultEnum.SUCCESS.getNo());
        response.setMsg(ResultEnum.SUCCESS.getDes());
        return response;
    }

    @PostMapping("/getOperationsByTkMapper")
    public BaseResponse<List<OperationLog>> getOperationsByTkMapper(@RequestBody BaseRequest<OperationLogDto> reqDto){
        BaseResponse<List<OperationLog>> response = new BaseResponse<>();
        List<OperationLog> operationLogs = operationLogService.getOperationsByTkMapper(reqDto.getData());
        response.setData(operationLogs);
        response.setCode(ResultEnum.SUCCESS.getNo());
        response.setMsg(ResultEnum.SUCCESS.getDes());
        logger.info("result: {}", operationLogs.size());
        return response;
    }

    @PostMapping("/getOperations")
    public void getOperations(@RequestBody OperationLogDto  reqDto){
        List<OperationLog> operationLogs = operationLogService.selectListByDto(reqDto);
        logger.info("result: {}", operationLogs.size());
    }

    @PostMapping("/getCustomerDetail")
    public BaseResponse<CustomerDto> getCustomerDetail(@RequestBody BaseRequest<GenericIdRequest> request){
        BaseResponse<CustomerDto> response = new BaseResponse<>();
        Customer customer = customerTKService.getCustomerById(request.getData().getId());
        CustomerDto customerDto = CustomerConvert.convertCustomer2Dto(customer);
        response.setData(customerDto);
        response.setCode(ResultEnum.SUCCESS.getNo());
        response.setMsg(ResultEnum.SUCCESS.getDes());
        return response;
    }

    @PostMapping("/updateCustomer")
    public BaseResponse<Boolean> updateCustomer(@RequestBody BaseRequest<SaveOrEditCustomerReqDto> request){
        BaseResponse<Boolean> response = new BaseResponse<>();
        SaveOrEditCustomerReqDto reqDto = request.getData();
        // 经纪人 和 主号不能缺失
        if(Objects.isNull(reqDto.getAgentId()) || StringUtils.isBlank(reqDto.getMainMobile())){
            response.setCode(ResultEnum.FAIL.getNo());
            response.setMsg(ResultEnum.FAIL.getDes());
            return response;
        }

        CustomerDto customerDto = new CustomerDto();
        BeanUtils.copyProperties(request.getData(), customerDto);
        customerTKService.saveOrEditCustomer(customerDto);

        response.setData(Boolean.TRUE);
        response.setCode(ResultEnum.SUCCESS.getNo());
        response.setMsg(ResultEnum.SUCCESS.getDes());
        return response;
    }
    
    @PostMapping("/getAccessToken")
    public String getAccessToken(@RequestBody CommonReqDTO request){
    	return wxAccessTokenCacheUtils.getAccessTokenBySystemId(request.getCompanyUuid(), request.getLoginType(), null);
    }
    
    @PostMapping("/castRefershAccessToken")
    public void castRefershAccessToken(@RequestBody CommonReqDTO request){
    	wxAccessTokenCacheUtils.remove(request.getCompanyUuid(), request.getLoginType());
    }
    
    /**
     * 案场助手到访审核一分为2，刷新权限
     */
    @GetMapping("/refreshVisitAuthority")
    public void refreshVisitAuthority(String companyId) {
    	logger.info("TestController->refreshVisitAuthority->start");
    	roleResourcesService.refreshVisitAuthority(companyId);
    	logger.info("TestController->refreshVisitAuthority->end");
    }

    @PostMapping("/getCustomerPage")
    public BaseResponse<PageResult<CustomerPageResDto>> getCustomerPage(@RequestBody PageRequest<GetCustomerPageReqDto> request){
        BaseResponse<PageResult<CustomerPageResDto>> response = new BaseResponse<>();
        PageResult<CustomerPageResDto> pageResult = new PageResult<>();

        String userId = request.getUserId();
        if(StringUtils.isBlank(userId)) {
            response.setCode(ResultEnum.USER_IS_NULL.getNo());
            response.setMsg(ResultEnum.USER_IS_NULL.getDes());
            return response;
        }
        request.getSearchDTO().setUserId(Long.valueOf(userId));
        int count = customerTKService.getWeappCustomerCount(request.getSearchDTO());
        List<Customer> customerList = customerTKService.getWeappCustomerPage(request.getSearchDTO(), request.getPageDTO());
        List<CustomerPageResDto> resDtoList = customerList.stream()
                .map(item -> CustomerConvert.convertCustomer2PageResDto(item, null))
                .collect(Collectors.toList());
        pageResult.setCount(Long.valueOf(count));
        pageResult.setList(resDtoList);
        response.setData(pageResult);
        return response;
    }

    @PostMapping("/getUserCache")
    public BaseResponse<Map<String, List<Long>>> getUserCache(@RequestBody GenericIdRequest request){
        BaseResponse<Map<String, List<Long>>> response = new BaseResponse<>();
        Map<String, List<Long>> permissionMap = new HashMap<>();
        PartnerInfo partnerInfo = partnerInfoService.selectById(request.getId());
        String roleOrgPermissionKey = RedisKeyConstant.Permission.DEV_ROLE_ORG_PERMISSION + partnerInfo.getUserRoleId();
        String userOrgPermissionKey = RedisKeyConstant.Permission.DEV_USER_ORG_PERMISSION + request.getId();
        String userPremisesPermissionKey = RedisKeyConstant.Permission.DEV_USER_PREMISES_PERMISSION + request.getId();

        List<Long> premisesIds = new ArrayList<>();
        Object object = RedisUtil.get(userPremisesPermissionKey);
        if(Objects.nonNull(object)){
            premisesIds = (List<Long>)object;
        }
        permissionMap.put("Premises", premisesIds);
        List<Long> permissionDeptIds = new ArrayList<>();
        if(RedisUtil.hasKey(userOrgPermissionKey)){
            object = RedisUtil.get(userOrgPermissionKey);
            if(Objects.nonNull(object)){
                permissionDeptIds = (List<Long>)object;
            }else {
                if(RedisUtil.hasKey(roleOrgPermissionKey)){
                    object = RedisUtil.get(roleOrgPermissionKey);
                    if(Objects.nonNull(object)){
                        permissionDeptIds = (List<Long>)object;
                    }
                }
            }
        }
        permissionMap.put("Dept", permissionDeptIds);
        response.setData(permissionMap);
        return response;
    }
}
